//
//  MYGAcademicLiveHeaderView.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/28.
//

import UIKit
import BetterSegmentedControl

class MYGAcademicLiveHeaderView: UIView {
    var detailModel = MYGMeetDetailModel()

    var dateModels = [MYGMeetDateModel]()
    var getDetailModelCompletion:((MYGMeetDetailDataModel)->Void)?
    var meeting_id:String = ""
    
    var line: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "eeeeee")
        return control
    }()
    
    var liveTitle:UILabel = {
        let control = UILabel()
        control.text = "现场直播"
        control.font = .medium(18)
        control.textColor = UIColor.init(hexString: "464646")
        return control
    }()
    
    var watchTitle:UILabel = {
        let control = UILabel()
        control.text = "观看量"
        control.font = .regular(11)
        control.textColor = UIColor.init(hexString: "999999")
        return control
    }()
    
    var watchContent:UILabel = {
        let control = UILabel()
        control.text = "234567"
        control.font = .regular(13)
        control.textColor = UIColor.init(hexString: "323232")
        return control
    }()

    var lineMid: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "eeeeee")
        return control
    }()
    
    var subTileView:MYGAcademicDetailSubtitleView = {
        let control = Bundle.main.loadNibNamed("MYGAcademicDetailSubtitleView", owner: nil)?.first as! MYGAcademicDetailSubtitleView
        control.reserveBtn.isHidden = true
        control.line.isHidden = true
        control.titleLB.isHidden = true
        control.liveLB.isHidden = true
        control.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 80)
        return control
    }()
    
    
    lazy var dateCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 11
        var leftMargin = 18.0
        layout.itemSize = CGSize(width: 39, height: 44)
        let control = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        control.register(UINib.init(nibName: "MYGAcademicDetailDateCell", bundle: nil), forCellWithReuseIdentifier: "MYGAcademicDetailDateCell")
        
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.contentInset = UIEdgeInsets(top: 0, left: leftMargin, bottom: 0, right: leftMargin)
        return control
    }()
    
    
    var lineBottom: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "eeeeee")
        return control
    }()
    
    lazy var segMent:BetterSegmentedControl = {
        let navigationSegmentedControl = BetterSegmentedControl(
            frame: .zero,
            segments: LabelSegment.segments(withTitles: [],
                                            normalTextColor: UIColor.init(hexString: "696969"),
                                            selectedTextColor:.white ),
            options:[.backgroundColor(UIColor.init(hexString: "f8f8f8")),
                     .indicatorViewBackgroundColor(UIColor.init(hexString: "ffb701")),
                     .cornerRadius(20),
                     .animationSpringDamping(1.0)])
        
        navigationSegmentedControl.addTarget(self,
                                             action: #selector(navigationSegmentedControlValueChanged(_:)),
                                             for: .valueChanged)
        return navigationSegmentedControl
    }()
    
    private lazy var scrollView: UIScrollView = {
        let sc = UIScrollView()
        sc.bounces = true
        sc.alwaysBounceHorizontal = true
        sc.showsHorizontalScrollIndicator = false
        return sc
    }()
    
    private lazy var contentView: UIView = {
        let contentView = UIView()
        contentView.backgroundColor = .white
        return contentView
    }()
    
    @objc func navigationSegmentedControlValueChanged(_ sender: BetterSegmentedControl) {
        let model = self.detailModel.data[sender.index]
        self.getDetailModelCompletion?(model)
    }
    
    func bindDatwModel(dateModels:[MYGMeetDateModel]) {
        self.dateModels = dateModels
        self.dateCollectionView.reloadData()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.dateCollectionView.delegate?.collectionView?(self.dateCollectionView, didSelectItemAt: IndexPath(row: 0, section: 0))
        })
    }
    //会议详情
    func getMeetDetail(model:MYGMeetDateModel) {
        self.subTileView.model = model
        MYGLoading.show()
        MYGNetwork<MYGHomePageAPI, MYGMeetDetailModel>.request(target: .meetingDetail(param: ["meeting_id":meeting_id,"date":model.date])) {[weak self] result in
            MYGLoading.hide()
            guard let `self` = self else {return}
            self.detailModel = result
            self.bindData()

        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func bindData() {
        var titles = [String]()
        for(_,obj) in self.detailModel.data.enumerated() {
            titles.append(obj.roomCn)
        }
        segMent.segments = LabelSegment.segments(withTitles: titles,
                                    normalTextColor: UIColor.init(hexString: "696969"),
                                    selectedTextColor:.white)
        
        self.liveTitle.text = self.detailModel.title
        self.watchContent.text = self.detailModel.heat
        if let c = getDetailModelCompletion {
            c(self.detailModel.data.first!)
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initSubViews()
        bindData()
    }
    
    
    func initSubViews() {
        backgroundColor = .white
        addSubview(line)
        line.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        addSubview(liveTitle)
        liveTitle.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(17.5)
        }
        
        addSubview(watchTitle)
        watchTitle.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(17.5)
            make.top.equalTo(liveTitle.snp.bottom).offset(9)
        }
        
        addSubview(watchContent)
        watchContent.snp.makeConstraints { make in
            make.left.equalTo(watchTitle.snp.right).offset(8)
            make.centerY.equalTo(watchTitle.snp.centerY)
        }
        addSubview(lineMid)
        lineMid.snp.makeConstraints { make in
            make.top.equalTo(watchTitle.snp.bottom).offset(17)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        addSubview(subTileView)
        subTileView.snp.makeConstraints { make in
            make.top.equalTo(lineMid.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(80)
        }
        
        addSubview(dateCollectionView)
        dateCollectionView.snp.makeConstraints { make in
            make.top.equalTo(subTileView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        addSubview(lineBottom)
        lineBottom.snp.makeConstraints { make in
            make.top.equalTo(dateCollectionView.snp.bottom).offset(15)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(lineBottom.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
        }
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.top.equalTo(lineBottom.snp.bottom).offset(15)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(40)
        }
        contentView.addSubview(segMent)
        segMent.snp.makeConstraints { make in
            make.top.equalTo(lineBottom.snp.bottom).offset(15)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(40)
//            make.verticalEdges.equalToSuperview()
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension MYGAcademicLiveHeaderView:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.dateModels[indexPath.row]
        self.dateModels = self.dateModels.map({ obj in
            var result = obj
            result.isSelected = false
            if model.date == obj.date {
                result.isSelected = true
            }
            return result
        })
        self.dateCollectionView.reloadData()
        getMeetDetail(model: model)
        
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dateModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGAcademicDetailDateCell", for: indexPath) as! MYGAcademicDetailDateCell
        let model = dateModels[indexPath.row]
        cell.model = model
        return cell
        
    }
}
